<template>
  <div style="display: flex; flex-direction: column; height: 100%">
    <div class="top">
      <div class="main_btn">
        <div class="search" style="display: flex; gap: 5px">
          <HPlainButton @click="createDialog = true">创建编码</HPlainButton>
          <HPlainButton @click="printTemp">打印模版</HPlainButton>
        </div>
        <div style="display: flex; gap: 5px">
          <HPlainButton @click="lookTemp">预览</HPlainButton>
          <HPlainButton @click="print2">打印</HPlainButton>
        </div>
      </div>
      <div class="main main_input">
        <el-select
          v-model="value1"
          :filter-method="remoteMethod"
          :loading="loading"
          remote-show-suffix
          class="mr10"
          @change="changeSel"
          placeholder="请选择编码"
          filterable
          clearable
        >
          <el-option
            v-for="(item, index) in options1"
            :key="index"
            :value="item.id"
            :label="item.name + '  ' + item.code"
          />
        </el-select>
        <el-select
          v-model="value2"
          class="mr10_"
          placeholder="请选择商品"
          @change="changeSel2"
          filterable
          clearable
        >
          <el-option
            v-for="(item, index) in options2"
            :key="index"
            :value="item.id"
            :label="
              item.brand + ' ' + item.goodsModel + ' ' + item.goodsName + ' ' + item.goodsSpecName
            "
        /></el-select>
        <div class="text_print">
          <span class="spac">共{{ total }}条编码</span>
          <span class="spac">每页编码数：</span>
          <el-input-number
            :controls="false"
            v-model="input2"
            class="page_num"
            @input="inputchange"
          />
          <span class="spac">共{{ pages }}页</span>
          <span class="spac"
            >打印第
            <el-input-number
              :controls="false"
              v-model="input"
              @input="changeInputPages"
              :max="pages"
              class="page_num"
            />
            页</span
          >
        </div>
        <el-select
          v-model="value"
          class="mr10_mo spac_"
          :filter-method="nameMethod"
          :loading="loading2"
          remote-show-suffix
          placeholder="选择模版"
          size="large"
          filterable
          clearable
          @change="selectChange"
        >
          <el-option
            v-for="(item, index) in options3"
            :key="index"
            :value="item.id"
            :label="item.name"
            :disabled="item.status"
          />
        </el-select>
        <span class="spac_">
          单码打印数量: <span> {{ codeNum }}</span></span
        >&nbsp;
        <span class="spac_">
          单行排列数量: <span> {{ rowQty }}</span></span
        >&nbsp;
        <span class="spac_">
          打印总数量: <span> {{ codeNum * input2 }}</span></span
        >
      </div>
    </div>
    <div
      class="app-container"
      style="height: 100%"
      v-loading="printDataing"
      element-loading-text="加载中..."
    >
      <div class="app-container-inner" style="display: flex; flex-direction: column; flex: 1">
        <div class="header">
          <div class="left">
            <span>摘选10条数据预览 预览无误，点击右侧打印按钮执行打印</span>
          </div>
        </div>
        <!-- 预览 -->
        <div
          style="height: 100%; flex: 1; overflow: auto; background-color: #f1f1f1; padding: 12px"
        >
          <div v-if="lookShow" class="bg_card">
            <templateMain :itemData="printList"></templateMain>
          </div>
        </div>
        <!-- 打印 -->
        <div
          style="
            overflow: auto;
            display: none;
            height: 92%;
            background-color: #f1f1f1;
            padding: 12px;
          "
        >
          <div class="prin_card bg_card" v-if="printData">
            <templateMain2 :itemData="printList" :printData="printData"></templateMain2>
          </div>
        </div>
        <!-- 创建编码弹窗 -->
        <HModal v-model="createDialog" title="创建编码" :width="750">
          <CreateCodepopup @close-popup="createDialog = $event" />
        </HModal>
      </div>
    </div>
    <!-- 预览弹窗 -->
    <el-dialog v-model="lookShow2" title="预览" width="70%" top="8vh" class="lookshow2" draggable>
      <div style="overflow: auto; height: 70vh; background-color: #f1f1f1; padding: 14px">
        <div class="bg_card">
          <templateMain2 :itemData="printList" :printData="printData"> </templateMain2>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
  import { ref, onMounted, reactive, nextTick } from 'vue'
  import { useRouter } from 'vue-router'
  import templateMain from '@/views/code/online/module/templateMain.vue'
  import templateMain2 from '@/views/code/online/module/templateMaintwo.vue'
  import CreateCodepopup from '../../code/list/detail/components/createCodepopup/index.vue'
  import { ElMessage } from 'element-plus'
  import '@/utils/Print'
  import * as _ from 'lodash'
  import {
    codeBatchPageSelect,
    getPrintTemplateData,
    codeBatchGoodsPageSelect,
    printTemplateList,
    printTemplateGetDetail,
  } from '../../../api/code'
  import HPlainButton from '@/components/common/button/HPlainButton.vue'
  import HModal from '@/components/common/Modal/HModal.vue'
  import pageComponentName from '@/config/page-component-name'

  defineOptions({
    name: pageComponentName.snCode.codeingOnline,
  })

  const router = useRouter()
  const value = ref(null) //模版name搜索
  const input = ref(1)
  const input2 = ref(0)
  const loading2 = ref(false)
  const printList = ref(null)
  const printData = ref(null) //打印数据
  const total = ref(0) //共有数据
  const pages = ref(0) //共有页数
  const createDialog = ref(false)
  const options1 = ref(null)
  const options2 = ref(null)
  const options3 = ref(null)
  const printDataing = ref(null)
  const pageData = reactive({
    limit: 0,
    name: '',
    page: 0,
  })
  const pageData2 = reactive({
    limit: 0,
    name: '',
    page: 0,
  })
  const codeNum = ref(0)
  const rowQty = ref(0)
  const lookShow = ref(false) //查看模版
  const lookShow2 = ref(false) //预览弹窗
  const value1 = ref() //批次编码id
  const loading = ref(true)
  const indexSel = ref(0)
  const value2 = ref('') //商品id
  const digData = ref(null)
  const changeSel = (val) => {
    indexSel.value = val
    value2.value = null
    if (!val) {
      return
    }
    codeBatchGoodsPageSelect(pageData2, val).then((res) => {
      options2.value = res.data.data.rows
      total.value = 0
    })
  }
  // 商品选择
  const changeSel2 = (val) => {
    if (val) {
      options2.value.filter((o) => {
        if (o.id == val) {
          total.value = o.qty
          if (o.qty != 0) {
            if (total.value >= 10) {
              input2.value = 10
            } else {
              input2.value = total.value
            }
            pages.value = 1
            input.value = 1
          }
        }
      })
      value.value = null
    }
  }
  const remoteMethod = _.throttle((val: string) => {
    if (pageData.name !== val) {
      pageData.name = val
      getCodeBatchPageSelect()
    }
  }, 500)
  const getCodeBatchPageSelect = async () => {
    loading.value = true
    const res = await codeBatchPageSelect(pageData)
    loading.value = false
    options1.value = res.data.data.rows
  }

  const getPrintTemplateListParam = ref({
    limit: 0,
    name: '',
    page: 0,
  })
  const inputMod = async () => {
    loading2.value = true
    const res = await printTemplateList(getPrintTemplateListParam.value)
    if (res.data.success) {
      options3.value = res.data.data.rows
    } else {
      if (res.data.isError)
        ElMessage({
          showClose: true,
          message: res.data.message,
          type: 'error',
          duration: 4000,
        })
    }
    loading2.value = false
  }
  const printTemp = () => {
    router.push({ path: '/code/printtemp' })
  }
  // 预览
  const lookTemp = async () => {
    if (!value2.value) {
      ElMessage({
        type: 'warning',
        showClose: true,
        offset: 300,
        message: '请先选择预览数据！',
      })
      return
    }
    if (!value.value) {
      ElMessage({
        type: 'warning',
        showClose: true,
        offset: 300,
        message: '请先选择打印模版！',
      })
      return
    }
    getpeinData(true)
  }
  // 获取打印数据
  const getpeinData = async (val) => {
    printData.value = null
    printDataing.value = true
    let data = {
      batchGoodsId: value2.value,
      batchId: value1.value,
      limit: input2.value,
      page: input.value,
      printTempLateId: value.value,
    }
    const res = await getPrintTemplateData(data)
    if (res.data.success) {
      printData.value = res.data.data.row
      lookShow2.value = val
    } else {
      ElMessage({
        showClose: true,
        message: res.data.message,
        type: 'error',
        duration: 4000,
      })
    }
    printDataing.value = false
  }
  // 打印
  const print2 = async () => {
    if (!value2.value) {
      ElMessage({
        type: 'warning',
        showClose: true,
        offset: 300,
        message: '请先选择打印数据！',
      })
      return
    }
    if (!value.value) {
      ElMessage({
        type: 'warning',
        showClose: true,
        offset: 300,
        message: '请先选择打印模版！',
      })
      return
    }
    getpeinData(false)
    nextTick()
    Print('.prin_card', {
      onStart: function () {},
      onEnd: function () {},
    })
  }

  // 每页打印数
  const inputchange = (val) => {
    if (total.value < val) {
      ElMessage({
        type: 'warning',
        showClose: true,
        message: '最大数不能超过总数！',
      })
      input2.value = null
      nextTick(() => {
        input2.value = total.value
      })
      return
    }
    if (val <= 0) {
      nextTick(() => {
        input2.value = 1
        pages.value = 1
        input.value = 1
      })
      return
    }
    pages.value = Math.ceil(total.value / val) || 0
    if (input.value > pages.value) {
      input.value = pages.value
    }
  }
  const changeInputPages = (val) => {
    if (val <= 0) {
      nextTick(() => {
        pages.value = 1
        input.value = 1
      })
      return
    }
    if (val > pages.value) {
      nextTick(() => {
        input.value = pages.value
      })
    }
  }

  // 选择模版
  const selectChange = (val) => {
    getprinData(val)
  }
  // 获取打印模版数据
  const getprinData = (val) => {
    printTemplateGetDetail(val).then((res) => {
      if (res.data.success) {
        let tmp = res.data.data.row
        printList.value = JSON.parse(JSON.stringify(tmp))
        codeNum.value = printList.value.codeNum
        rowQty.value = printList.value.rowQty
        lookShow.value = true
      } else {
        if (res.data.isError)
          ElMessage({
            type: 'error',
            showClose: true,
            message: res.data.message,
            duration: 5000,
          })
      }
    })
  }
  // 模版名称搜索
  const nameMethod = _.throttle((val: string) => {
    if (!value1.value || !value2.value) {
      return
    }

    if (getPrintTemplateListParam.value.name !== val) {
      getPrintTemplateListParam.value.name = val
      inputMod()
    }
  }, 500)

  onMounted(() => {
    digData.value = JSON.parse(localStorage.getItem('digData'))
    getCodeBatchPageSelect()
    inputMod()
  })
</script>

<style scoped lang="scss">
  @import './index';
</style>
<style>
  @media print {
    @page {
      size: auto;
    }

    body,
    html {
      height: auto !important;
    }
  }
</style>
